import { Workbook, } from "exceljs";
import FileSaver from "file-saver";
import XLSX from "xlsx-js-style";
//导出配置
export var EXPORY_CONFIG;
(function (EXPORY_CONFIG) {
    EXPORY_CONFIG.exccelNumberFormat = '#,##0.00;-#,##0.00;"";@'; // 定义会计专用格式字符串,零值不显示 不行
    EXPORY_CONFIG.excelPercentFormat = '#,##0.00%;-#,##0.00%;"";@'; // 定义百分数表格式
    //默认页大小
    EXPORY_CONFIG.defaultSampePageSize = 50;
    EXPORY_CONFIG.numberFormat = "#,##0.00";
    EXPORY_CONFIG.percentFormat = { type: "percent", precision: 2 };
    EXPORY_CONFIG.percentFormat4Bit = { type: "percent", precision: 4 };
    EXPORY_CONFIG.numberFormat0 = "0.00";
    EXPORY_CONFIG.unitGeFormat = "#0 个";
    EXPORY_CONFIG.orderIndexFieldName = "orderIndex";
    EXPORY_CONFIG.excelRowIndexFieldName = "excelRowIndex";
    EXPORY_CONFIG.pixelsPerCharacter = 7.5;
    EXPORY_CONFIG.autoIncText = "自动编号";
    EXPORY_CONFIG.betweenText = "区间";
    EXPORY_CONFIG.equalText = "等于";
    EXPORY_CONFIG.includeText = "包含";
    EXPORY_CONFIG.decludeText = "不包含";
    EXPORY_CONFIG.startIsText = "左包含";
    EXPORY_CONFIG.endIsText = "右包含";
    EXPORY_CONFIG.empty = "";
    EXPORY_CONFIG.curNoValue = "(暂无)";
    EXPORY_CONFIG.noValue = "(无)";
    EXPORY_CONFIG.notQueryCondition = "<还未设置高级查询条件>";
    EXPORY_CONFIG.emptyText = "<空>";
    EXPORY_CONFIG.multiSeparator = "多个用逗号分隔";
    EXPORY_CONFIG.textOperatorArray = [
        EXPORY_CONFIG.empty,
        EXPORY_CONFIG.equalText,
        EXPORY_CONFIG.includeText,
        EXPORY_CONFIG.decludeText,
        EXPORY_CONFIG.startIsText,
        EXPORY_CONFIG.endIsText,
    ];
    EXPORY_CONFIG.asc = "asc";
    EXPORY_CONFIG.desc = "desc";
    EXPORY_CONFIG.sampleSortList = [
        { value: EXPORY_CONFIG.asc, text: "升序" },
        { value: EXPORY_CONFIG.desc, text: "降序" },
    ];
    //抽取方式(系统)
    EXPORY_CONFIG.extractMethodArray = [
        { value: EXPORY_CONFIG.asc, text: "自上而下的顺序抽取" },
        { value: EXPORY_CONFIG.desc, text: "自下而上的顺序抽取" },
    ];
    EXPORY_CONFIG.amountBigToSmall = "amountBigToSmall";
    EXPORY_CONFIG.amountSmallToBig = "amountSmallToBig";
    EXPORY_CONFIG.amountRandom = "amountRandom";
    //抽方式(分层)
    EXPORY_CONFIG.amountExtractMethodArray = [
        { value: EXPORY_CONFIG.amountBigToSmall, text: "金额由大到小的顺序抽取" },
        { value: EXPORY_CONFIG.amountSmallToBig, text: "金额由小到大的顺序抽取" },
        { value: EXPORY_CONFIG.amountRandom, text: "随机抽取" },
    ];
    EXPORY_CONFIG.jzpzStr = "记";
    EXPORY_CONFIG.maxSampleCount = 50000; //最大记录5万
    /**
     * 风险级别
     */
    EXPORY_CONFIG.riskLevelArray = [
        { value: "highest", text: "最高" },
        { value: "high", text: "高" },
        { value: "middle", text: "中" },
        { value: "low", text: "低" },
    ];
    EXPORY_CONFIG.assertions = [
        //  { value: "", text: "" },
        { value: "existence_occurrence", text: "存在/发生" } /*
          { value: "occurrence", text: "发生" }, */,
        { value: "completeness", text: "完整性" },
        { value: "rightsAndObligations", text: "权利和义务" },
        { value: "valuationAndAllocation", text: "计价和分摊" },
        { value: "classification", text: "分类" },
        { value: "presentation", text: "列报" },
        //  { value: "accuracy", text: "准确性" },
        //  { value: "cutoff", text: "截止" },
        //存在/发生、完整性、权利和义务、计价和分摊、分类、列报
        // { value: "completenessSpecific", text: "完整性（特定账户）" }
    ];
    EXPORY_CONFIG.NA = "N/A";
    EXPORY_CONFIG.randomSeed = 10000; //1万
    EXPORY_CONFIG.selectNullOrderFields = "(select null)";
    EXPORY_CONFIG.specialSampleType = "特殊样本";
    EXPORY_CONFIG.amountMajorSampleType = "金额重大";
    EXPORY_CONFIG.manualAddSampleType = "手工添加";
    EXPORY_CONFIG.normalSampleType = "普通样本";
    EXPORY_CONFIG.maxExportCount = 10 * 10000; //10万
    EXPORY_CONFIG.localBlobFileTag = "localBlobFile";
    EXPORY_CONFIG.sampledAllSampleSizeField = "sampleStepInfo.sampleParameterValues.sampledAllSampleSize";
    EXPORY_CONFIG.AcYesNoOnlyListOfEmpty = [
        { id: "是", text: "是" },
        { id: "否", text: "否" },
        { id: "", text: "(空)" },
    ];
    EXPORY_CONFIG.xh = "序号";
    EXPORY_CONFIG.JFJE_DFJE_Field = "ABS(JFJE)+ABS(DFJE)";
    EXPORY_CONFIG.JFJE_DFJE_ABS = `[${EXPORY_CONFIG.JFJE_DFJE_Field}]`;
    EXPORY_CONFIG.JFJE_DFJE_Field_SEP = ` [JFJE],[DFJE]`;
    EXPORY_CONFIG.JFJE_DFJE_Title = "借方或贷方金额";
})(EXPORY_CONFIG || (EXPORY_CONFIG = {}));
//文件基本名称 银行存款.docx
export function getFileBaseName(fileName) {
    if (!fileName)
        return fileName;
    let fileNameArr = fileName.replaceAll(/\\/g, "/").split("/");
    return fileNameArr[fileNameArr.length - 1];
}
//文件基本名称,不包含扩展: 银行存款.docx => 银行存款
export function getFileBaseNameOnly(fileName) {
    if (!fileName)
        return fileName;
    let fileBaseName = getFileBaseName(fileName);
    if (fileBaseName.indexOf(".") == -1)
        return fileName;
    let fileExt = getFileExtName(fileBaseName);
    return fileBaseName.substring(0, fileBaseName.length - fileExt.length); //
}
//文件扩展名, 如.docx
export function getFileExtName(fileName) {
    if (!fileName)
        return fileName;
    let fileBaseName = getFileBaseName(fileName);
    if (fileBaseName.indexOf(".") == -1)
        return "";
    let fileNameArr = fileBaseName.split(".");
    return "." + fileNameArr[fileNameArr.length - 1]; //
}
function getAlignByColumnAlignment(alignment) {
    return {
        horizontal: (alignment ? alignment : "left"),
        vertical: "middle",
    };
}
function getBorder() {
    return {
        top: { style: "thin" },
        left: { style: "thin" },
        bottom: { style: "thin" },
        right: { style: "thin" },
    };
}
function truncateSheetName(sheetName) {
    // 计算字符串长度，考虑中文字符
    const length = Array.from(sheetName).length;
    // 如果长度超过31个字符，则截取前31个字符
    if (length > 15) {
        sheetName = Array.from(sheetName).slice(0, 15).join("");
    }
    return sheetName;
}
/**
 *   导出Excel
 * @param columns
 * @param rowsData
 * @param defaultFileNameOnly
 */
export async function exportDataToExcel(columns, rowsData, fileFullName) {
    //大于50000用行xlsx导出。用exceljs有性能问题
    if (rowsData && rowsData.length > 50000) {
        return exportDataToExcelBySheetJs(columns, rowsData, fileFullName);
    }
    else {
        const excelColumns = columns
            .filter((column) => column.dataField && (column.visible == undefined || column.visible))
            .map((column) => {
            let columnWidth = column.width ? column.width / 7.5 : 15;
            let excleColumn = {
                header: [column.caption],
                key: column.dataField,
                width: columnWidth,
                style: {
                    alignment: getAlignByColumnAlignment(column.alignment),
                    border: getBorder(),
                    numFmt: column.format == EXPORY_CONFIG.numberFormat
                        ? EXPORY_CONFIG.exccelNumberFormat
                        : undefined,
                    font: {
                        name: column?.dataType === "number" ? "Arial Narrow" : "华文中宋",
                    },
                },
            };
            return excleColumn;
        });
        let sheetName = getFileBaseNameOnly(fileFullName).substring(0, 30); //30个汉字
        const workbook = new Workbook();
        const worksheet = workbook.addWorksheet(sheetName);
        // 设置固定第一行
        worksheet.views = [
            {
                ySplit: 1,
                state: "frozen", // 冻结视图状态
            },
        ];
        //数据过滤
        worksheet.autoFilter = {
            from: { row: 1, column: 1 },
            to: { row: 1, column: excelColumns.length },
        };
        worksheet.columns = excelColumns;
        //批量加数据(报表行)
        worksheet.addRows(rowsData);
        //标题行加粗
        excelColumns.forEach((column, index) => {
            const cell = worksheet.getCell(1, index + 1);
            cell.font = { bold: true }; // 加粗字体
        });
        const isErrorColumnIndex = worksheet.columns.findIndex((item) => item.key == "isError");
        //错报列加下拉,第2行开始
        if (isErrorColumnIndex > -1) {
            for (let row = 1; row < worksheet.rowCount; row++) {
                const cell = worksheet.getCell(row, isErrorColumnIndex + 1);
                cell.dataValidation = {
                    type: "list",
                    //excel下拉框
                    formulae: [
                        '"' +
                            EXPORY_CONFIG.AcYesNoOnlyListOfEmpty.map((item) => item.id).join(",") +
                            '"',
                    ],
                };
            }
        }
        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        /* 不生效,不知道传乱原因
             let localSavePathId = encodeURIComponent(sheetName);
             let localSavePath = encodeURIComponent(fileFullName);
             let outLocalFileName = consts.localBlobFileTag
                 + `?localSavePath=${localSavePath}&localSavePathId=${localSavePathId};`
          */
        FileSaver.saveAs(blob, fileFullName);
    }
}
// const borderStyle = { style: "thin", color: { argb: "000000" } };
const borderStyle = { style: "thin", color: { argb: "000000" } };
/**
通过sheetjs输出,26行 大约1分钟
大于5万行的,用新方式,但没有格式,且右键全部导出还是导出不了,需要找丁肖飞改
@param columns
@param rowsData
@param fileFullName
*/
function getExcelColumns(columns) {
    const excelColumns = columns
        .filter((column) => column.dataField && (column.visible == undefined || column.visible))
        .map((column) => {
        let columnWidth = column.width ? column.width / 7.5 : 15;
        let excleColumn = {
            header: [column.caption],
            key: column.dataField,
            width: columnWidth,
            style: {
                alignment: getAlignByColumnAlignment(column.alignment),
                border: getBorder(),
                numFmt: column.format == EXPORY_CONFIG.numberFormat
                    ? EXPORY_CONFIG.exccelNumberFormat
                    : undefined,
            },
        };
        return excleColumn;
    });
    return excelColumns;
}
export async function exportDataToExcelBySheetJs(columns, rowsData, fileFullName) {
    const excelColumns = getExcelColumns(columns);
    //转为xlsx的数据格式
    let ws_data = [
        excelColumns.map((column) => Array.isArray(column.header) ? column.header[0] : column.header),
    ]; //表头
    ws_data = ws_data.concat(rowsData.map((rowData) => excelColumns.map((column) => rowData[column.key || ""])));
    //生成有单元格样式的,这里如果数据量大了,这个会失效
    const opts = { cellStyles: true };
    const ws = XLSX.utils.aoa_to_sheet(ws_data);
    //区域
    const range = {
        s: { c: 0, r: 0 },
        e: { c: excelColumns.length - 1, r: rowsData.length - 1 },
    };
    // 设置自动筛选，//'A1:G111' // 指定自动筛选的范围
    ws["!autofilter"] = { ref: XLSX.utils.encode_range(range) };
    //不行ws['!freeze'] ={ xSplit: 0, ySplit: 1, topLeftCell: 'A2', activePane: 'bottomLeft' };
    //列宽宽度
    ws["!cols"] = excelColumns.map((column) => ({ wch: column.width }));
    // 为指定区域添加边框,这里如果数据量大了,这个会失效
    for (let rowNum = range.s.r; rowNum <= range.e.r; rowNum++) {
        for (let colNum = range.s.c; colNum <= range.e.c; colNum++) {
            const cellAddress = XLSX.utils.encode_cell({ r: rowNum, c: colNum });
            if (!ws[cellAddress]) {
                ws[cellAddress] = { t: "s", v: "" }; // 如果单元格为空，则创建一个空单元格
            }
            const numFmt = excelColumns[colNum]?.style?.numFmt;
            ws[cellAddress].s = { border: borderStyle, numFmt };
        }
    }
    var wb = XLSX.utils.book_new();
    let sheetName = getFileBaseNameOnly(fileFullName).substring(0, 30); //30个汉字
    XLSX.utils.book_append_sheet(wb, ws, sheetName);
    XLSX.writeFileXLSX(wb, `${fileFullName}`, opts);
}
